// 组件工厂
// 提供统一的组件创建、优化、增强功能

import React, { ComponentType, forwardRef, memo, lazy, Suspense } from 'react';
import { FullBaseProps, withPerformanceMonitoring, withErrorBoundary, withLazyLoading } from '../base/BaseComponent';
import { useTheme, useComponentTheme } from '../theme/ThemeProvider';
import { useLayout } from '../layout/ResponsiveLayout';

// 组件工厂配置
export interface ComponentFactoryConfig {
  // 性能优化
  memo?: boolean;
  lazy?: boolean;
  preload?: boolean;
  
  // 错误处理
  errorBoundary?: boolean;
  fallback?: ComponentType<{ error: Error; retry: () => void }>;
  
  // 性能监控
  performanceMonitoring?: boolean;
  
  // 主题支持
  themed?: boolean;
  themeKey?: string;
  
  // 响应式支持
  responsive?: boolean;
  
  // 可访问性
  accessibility?: boolean;
  
  // 开发工具
  devTools?: boolean;
}

// 默认配置
const defaultConfig: ComponentFactoryConfig = {
  memo: true,
  lazy: false,
  preload: false,
  errorBoundary: true,
  performanceMonitoring: process.env.NODE_ENV === 'development',
  themed: true,
  responsive: true,
  accessibility: true,
  devTools: process.env.NODE_ENV === 'development',
};

// 组件增强器类型
export type ComponentEnhancer<P = any> = (
  Component: ComponentType<P>
) => ComponentType<P>;

// 创建组件工厂
export function createComponentFactory<P extends FullBaseProps>(
  Component: ComponentType<P>,
  config: ComponentFactoryConfig = {}
): ComponentType<P> {
  const finalConfig = { ...defaultConfig, ...config };
  let EnhancedComponent = Component;

  // 应用memo优化
  if (finalConfig.memo) {
    EnhancedComponent = memo(EnhancedComponent);
  }

  // 应用性能监控
  if (finalConfig.performanceMonitoring) {
    EnhancedComponent = withPerformanceMonitoring(
      EnhancedComponent,
      Component.displayName || Component.name || 'Component'
    );
  }

  // 应用错误边界
  if (finalConfig.errorBoundary) {
    EnhancedComponent = withErrorBoundary(EnhancedComponent, finalConfig.fallback);
  }

  // 应用懒加载
  if (finalConfig.lazy) {
    EnhancedComponent = withLazyLoading(EnhancedComponent);
  }

  // 应用主题支持
  if (finalConfig.themed) {
    EnhancedComponent = withTheme(EnhancedComponent, finalConfig.themeKey);
  }

  // 应用响应式支持
  if (finalConfig.responsive) {
    EnhancedComponent = withResponsive(EnhancedComponent);
  }

  // 应用可访问性增强
  if (finalConfig.accessibility) {
    EnhancedComponent = withAccessibility(EnhancedComponent);
  }

  // 应用开发工具
  if (finalConfig.devTools) {
    EnhancedComponent = withDevTools(EnhancedComponent);
  }

  return EnhancedComponent;
}

// 主题增强器
export function withTheme<P extends FullBaseProps>(
  Component: ComponentType<P>,
  themeKey?: string
): ComponentType<P> {
  const ThemedComponent = forwardRef<any, P>((props, ref) => {
    const { currentTheme } = useTheme();
    const componentTheme = useComponentTheme(themeKey || 'button');

    const themedProps = {
      ...props,
      theme: currentTheme,
      componentTheme,
    };

    return <Component {...themedProps} ref={ref} />;
  });

  ThemedComponent.displayName = `withTheme(${Component.displayName || Component.name})`;
  return ThemedComponent;
}

// 响应式增强器
export function withResponsive<P extends FullBaseProps>(
  Component: ComponentType<P>
): ComponentType<P> {
  const ResponsiveComponent = forwardRef<any, P>((props, ref) => {
    const layout = useLayout();

    const responsiveProps = {
      ...props,
      layout,
      viewport: layout.viewport,
      breakpoint: layout.currentBreakpoint,
      isMobile: layout.isMobile,
      isTablet: layout.isTablet,
      isDesktop: layout.isDesktop,
    };

    return <Component {...responsiveProps} ref={ref} />;
  });

  ResponsiveComponent.displayName = `withResponsive(${Component.displayName || Component.name})`;
  return ResponsiveComponent;
}

// 可访问性增强器
export function withAccessibility<P extends FullBaseProps>(
  Component: ComponentType<P>
): ComponentType<P> {
  const AccessibleComponent = forwardRef<any, P>((props, ref) => {
    const {
      'aria-label': ariaLabel,
      'aria-describedby': ariaDescribedBy,
      role,
      tabIndex,
      ...restProps
    } = props;

    // 自动生成可访问性属性
    const accessibilityProps = {
      ...restProps,
      'aria-label': ariaLabel || generateAriaLabel(props),
      'aria-describedby': ariaDescribedBy,
      role: role || inferRole(Component),
      tabIndex: tabIndex !== undefined ? tabIndex : (props.disabled ? -1 : 0),
    };

    return <Component {...accessibilityProps} ref={ref} />;
  });

  AccessibleComponent.displayName = `withAccessibility(${Component.displayName || Component.name})`;
  return AccessibleComponent;
}

// 开发工具增强器
export function withDevTools<P extends FullBaseProps>(
  Component: ComponentType<P>
): ComponentType<P> {
  const DevToolsComponent = forwardRef<any, P>((props, ref) => {
    const [renderCount, setRenderCount] = React.useState(0);
    const [lastRenderTime, setLastRenderTime] = React.useState(0);

    React.useEffect(() => {
      setRenderCount(prev => prev + 1);
      setLastRenderTime(Date.now());
    });

    // 在开发环境下添加调试信息
    const devProps = process.env.NODE_ENV === 'development' ? {
      ...props,
      'data-render-count': renderCount,
      'data-last-render': lastRenderTime,
      'data-component-name': Component.displayName || Component.name,
    } : props;

    return <Component {...devProps} ref={ref} />;
  });

  DevToolsComponent.displayName = `withDevTools(${Component.displayName || Component.name})`;
  return DevToolsComponent;
}

// 组合多个增强器
export function compose<P extends FullBaseProps>(
  Component: ComponentType<P>,
  ...enhancers: ComponentEnhancer<P>[]
): ComponentType<P> {
  return enhancers.reduce((acc, enhancer) => enhancer(acc), Component);
}

// 创建变体组件
export function createVariant<P extends FullBaseProps>(
  BaseComponent: ComponentType<P>,
  variantProps: Partial<P>,
  variantName: string
): ComponentType<P> {
  const VariantComponent = forwardRef<any, P>((props, ref) => {
    const mergedProps = { ...variantProps, ...props };
    return <BaseComponent {...mergedProps} ref={ref} />;
  });

  VariantComponent.displayName = `${BaseComponent.displayName || BaseComponent.name}${variantName}`;
  return VariantComponent;
}

// 创建复合组件
export function createCompound<P extends FullBaseProps>(
  components: Record<string, ComponentType<any>>,
  MainComponent: ComponentType<P>
): ComponentType<P> & Record<string, ComponentType<any>> {
  const CompoundComponent = MainComponent as ComponentType<P> & Record<string, ComponentType<any>>;
  
  Object.entries(components).forEach(([key, Component]) => {
    CompoundComponent[key] = Component;
  });

  return CompoundComponent;
}

// 工具函数：生成ARIA标签
function generateAriaLabel(props: any): string | undefined {
  if (props.children && typeof props.children === 'string') {
    return props.children;
  }
  if (props.title) {
    return props.title;
  }
  if (props.placeholder) {
    return props.placeholder;
  }
  return undefined;
}

// 工具函数：推断角色
function inferRole(Component: ComponentType<any>): string | undefined {
  const name = Component.displayName || Component.name || '';
  
  if (name.toLowerCase().includes('button')) {
    return 'button';
  }
  if (name.toLowerCase().includes('input')) {
    return 'textbox';
  }
  if (name.toLowerCase().includes('link')) {
    return 'link';
  }
  if (name.toLowerCase().includes('modal')) {
    return 'dialog';
  }
  if (name.toLowerCase().includes('menu')) {
    return 'menu';
  }
  
  return undefined;
}

// 预设的组件工厂配置
export const presetConfigs = {
  // 基础组件配置
  basic: {
    memo: true,
    errorBoundary: true,
    themed: true,
    accessibility: true,
  },
  
  // 高性能组件配置
  performance: {
    memo: true,
    lazy: true,
    performanceMonitoring: true,
    errorBoundary: true,
  },
  
  // 响应式组件配置
  responsive: {
    memo: true,
    themed: true,
    responsive: true,
    accessibility: true,
  },
  
  // 开发组件配置
  development: {
    memo: false,
    performanceMonitoring: true,
    errorBoundary: true,
    devTools: true,
  },
  
  // 生产组件配置
  production: {
    memo: true,
    lazy: true,
    errorBoundary: true,
    performanceMonitoring: false,
    devTools: false,
  },
} as const;

// 快捷创建函数
export const createBasicComponent = <P extends FullBaseProps>(Component: ComponentType<P>) =>
  createComponentFactory(Component, presetConfigs.basic);

export const createPerformanceComponent = <P extends FullBaseProps>(Component: ComponentType<P>) =>
  createComponentFactory(Component, presetConfigs.performance);

export const createResponsiveComponent = <P extends FullBaseProps>(Component: ComponentType<P>) =>
  createComponentFactory(Component, presetConfigs.responsive);

// 组件注册和管理
class ComponentManager {
  private components = new Map<string, ComponentType<any>>();
  private variants = new Map<string, Map<string, ComponentType<any>>>();

  register<P extends FullBaseProps>(
    name: string,
    Component: ComponentType<P>,
    config?: ComponentFactoryConfig
  ): void {
    const EnhancedComponent = createComponentFactory(Component, config);
    this.components.set(name, EnhancedComponent);
  }

  registerVariant<P extends FullBaseProps>(
    baseName: string,
    variantName: string,
    Component: ComponentType<P>,
    config?: ComponentFactoryConfig
  ): void {
    const EnhancedComponent = createComponentFactory(Component, config);
    
    if (!this.variants.has(baseName)) {
      this.variants.set(baseName, new Map());
    }
    
    this.variants.get(baseName)!.set(variantName, EnhancedComponent);
  }

  get(name: string): ComponentType<any> | undefined {
    return this.components.get(name);
  }

  getVariant(baseName: string, variantName: string): ComponentType<any> | undefined {
    return this.variants.get(baseName)?.get(variantName);
  }

  list(): string[] {
    return Array.from(this.components.keys());
  }

  listVariants(baseName: string): string[] {
    return Array.from(this.variants.get(baseName)?.keys() || []);
  }
}

// 全局组件管理器
export const componentManager = new ComponentManager();

// 导出所有工具
export {
  defaultConfig,
  ComponentManager,
};
